<template>
	<view class="shop-container">
		<!-- 背景装饰 -->
		<view class="bg-decoration"></view>

		<!-- 数据统计卡片 -->
		<view class="stats-cards">
			<view class="stat-card">
				<view class="decoration"></view>
				<text class="number">¥{{ formatAmount(shopStats.extraIncome) }}</text>
				<text class="label">额外营收</text>
			</view>
			<view class="stat-card">
				<view class="decoration"></view>
				<text class="number">{{ formatNumber(shopStats.activeUsers) }}</text>
				<text class="label">日活用户</text>
			</view>
			<view class="stat-card">
				<view class="decoration"></view>
				<text class="number">{{ formatNumber(shopStats.pendingDelivery) }}</text>
				<text class="label">待处理订单</text>
			</view>
		</view>

		<!-- 店铺管理区域 -->
		<view class="section-wrapper">
			<view class="section-title">店铺管理</view>
			<view class="action-buttons">
				<view class="action-btn" @tap="navigateToAddProduct">
					<view class="btn-icon">
						<uv-icon custom-prefix="custom-icon" name="shangjia1" size="36" color="#3c9cff"></uv-icon>
					</view>
					<text class="btn-text">添加商品</text>
				</view>
				<view class="action-btn" @tap="navigateToProductManage">
					<view class="btn-icon">
						<uv-icon custom-prefix="custom-icon" name="s-goods" size="36" color="#3c9cff"></uv-icon>
					</view>
					<text class="btn-text">商品管理</text>
				</view>
			</view>
		</view>

		<!-- 订单管理区域 -->
		<view class="section-wrapper">
			<view class="section-title">订单管理</view>
			<view class="action-buttons">
				<view class="action-btn" @tap="navigateToOrderList">
					<view class="btn-icon">
						<uv-icon custom-prefix="custom-icon" name="order-fill" size="36" color="#3c9cff"></uv-icon>
					</view>
					<text class="btn-text">订单列表</text>
					<view class="badge" v-if="shopStats.pendingDelivery > 0">
						{{ formatBadgeNumber(shopStats.pendingDelivery) }}
					</view>
				</view>
				<view class="action-btn" @tap="navigateToDelivery">
					<view class="btn-icon">
						<uv-icon custom-prefix="custom-icon" name="baoguofahuo" size="36" color="#3c9cff"></uv-icon>
					</view>
					<text class="btn-text">发货管理</text>
				</view>
			</view>
		</view>

		<!-- 数据分析图表区域 -->
		<view class="section-wrapper chart-section">
			<view class="section-title">数据趋势</view>
			<view class="chart-tabs">
				<text class="tab-item" :class="{ active: activeChart === 'users' }"
					@tap="switchChart('users')">用户趋势</text>
				<text class="tab-item" :class="{ active: activeChart === 'orders' }"
					@tap="switchChart('orders')">订单趋势</text>
			</view>
			<canvas canvas-id="trendChart" id="trendChart" class="trend-chart" @touchend="tap" />
		</view>
	</view>
</template>

<script>
import uCharts from '@/uchart/u-charts-v2.5.0-20230101.js';
var uChartsInstance = {};

export default {
	data() {
		return {
			merchantId: null,
			shopStats: {
				extraIncome: 32805.50,
				activeUsers: 15678,
				pendingDelivery: 0
			},
			cWidth: 0,
			cHeight: 0,
			activeChart: 'users',
			chartData: {
				users: {
					categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
					series: [{
						name: '日活用户',
						data: [156, 230, 184, 234, 290, 330, 310]
					}]
				},
				orders: {
					categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
					series: [{
						name: '日下单量',
						data: [23, 45, 32, 56, 78, 89, 76]
					}]
				}
			}
		}
	},
	methods: {
		navigateToAddProduct() {
			uni.navigateTo({
				url: '/subpkg/add_goods/add_goods'
			})
		},
		navigateToProductManage() {
			uni.navigateTo({
				url: `/subpkg/merchant_goods_manage/merchant_goods_manage?merchantId=${this.merchantId}`
			})
		},
		navigateToOrderList() {
			uni.navigateTo({
				url: `/subpkg/merchant_order_list/merchant_order_list?merchantId=${this.merchantId}`
			})
		},
		navigateToDelivery() {
			uni.navigateTo({
				url: '/subpkg/goods_delivery/goods_delivery?merchantId=' + this.merchantId
			})
		},
		// 切换图表
		switchChart(type) {
			this.activeChart = type;
			this.drawTrendChart();
		},

		// 绘制趋势图表
		drawTrendChart() {
			const data = this.chartData[this.activeChart];
			const ctx = uni.createCanvasContext('trendChart', this);
			uChartsInstance['trendChart'] = new uCharts({
				type: 'line',
				context: ctx,
				width: this.cWidth,
				height: this.cHeight,
				categories: data.categories,
				series: data.series,
				animation: true,
				background: '#FFFFFF',
				color: ['#3c9cff'],
				padding: [15, 15, 15, 15],
				enableScroll: false,
				legend: {
					show: false
				},
				xAxis: {
					disableGrid: true,
					fontColor: '#666666',
					fontSize: 12,
				},
				yAxis: {
					gridType: 'dash',
					dashLength: 2,
					data: [{
						min: 0
					}],
					fontColor: '#666666',
					fontSize: 12,
				},
				extra: {
					line: {
						type: 'straight',
						width: 2,
						activeType: 'hollow'
					},
					tooltip: {
						showBox: true,
						borderWidth: 0,
						borderRadius: 3,
						borderColor: '#000000',
						borderOpacity: 0.7,
						bgColor: '#000000',
						bgOpacity: 0.7,
						fontColor: '#FFFFFF'
					}
				}
			});
		},

		// 图表交互处理
		tap(e) {
			uChartsInstance[e.target.id].touchLegend(e);
			uChartsInstance[e.target.id].showToolTip(e);
		},

		// 格式化金额
		formatAmount(amount) {
			if (!amount && amount !== 0) return '0.00';

			// 处理万以上的金额
			if (amount >= 10000) {
				const wan = (amount / 10000).toFixed(1);
				return wan + 'w';
			}

			// 普通金额保留两位小数
			return amount.toFixed(2);
		},

		// 格式化数字
		formatNumber(num) {
			if (!num && num !== 0) return '0';

			// 处理万以上的数字
			if (num >= 10000) {
				const wan = (num / 10000).toFixed(1);
				return wan + 'w';
			}

			// 处理千以上的数字
			if (num >= 1000) {
				const qian = (num / 1000).toFixed(1);
				return qian + 'k';
			}

			return num.toString();
		},

		// 后端数据格式化方法
		formatStatsData(data) {
			return {
				extraIncome: parseFloat(data.extraIncome) || 0,
				activeUsers: parseInt(data.activeUsers) || 0,
				pendingDelivery: parseInt(data.pendingDelivery) || 0
			};
		},

		// 获取统计数据的方法（示例）
		async fetchStatsData() {
			try {
				const res = await this.$http.get('/api/shop/stats', {
					params: {
						merchantId: this.merchantId
					}
				});
				if (res?.code === 200) {
					const data = res.data;
					this.shopStats = {
						...this.shopStats,
						extraIncome: parseFloat(data.extraIncome) || 0,
						activeUsers: parseInt(data.activeUsers) || 0
					};
				}
			} catch (error) {
				// console.error('获取统计数据失败:', error);
				// uni.showToast({
				// 	title: '获取数据失败',
				// 	icon: 'none'
				// });
			}
		},

		// 格式化徽标数字
		formatBadgeNumber(num) {
			return num > 99 ? '99+' : num.toString();
		},

		// 获取订单数量
		async fetchOrderCount() {
			try {
				const res = await this.$http.get(`/merchant/order/count?merchantId=${this.merchantId}`);
				
				if (res) {
					this.shopStats.pendingDelivery = res || 0;
				}
			} catch (error) {
				console.error('获取订单数量失败:', error);
			}
		}
	},

	onReady() {
		const sys = uni.getSystemInfoSync();
		this.cWidth = sys.windowWidth - 80; // 减去左右padding
		this.cHeight = 200;
		this.drawTrendChart();
	},

	// 页面加载时获取数据
	onLoad(options) {
		this.merchantId = options.merchantId;
		if (!this.merchantId) {
			uni.showToast({
				title: '缺少商家ID参数',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
			return;
		}
		
		this.fetchStatsData();
		this.fetchOrderCount(); // 获取订单数量
	},

	// 页面显示时刷新订单数量
	onShow() {
		if (this.merchantId) {
			this.fetchOrderCount();
		}
	}
}
</script>

<style lang="scss" scoped>
@import 'my_shop.scss';
</style>